package org.wmq.taskschedule.algorithm;

import org.opencv.core.Core;
import org.opencv.core.Mat;
import org.opencv.imgproc.Imgproc;

/**
 * 直方图均衡化算法执行器
 * 实现AlgorithmExecutor接口，用于对图像进行直方图均衡化处理
 */
public class HistogramEqualizationExecutor implements AlgorithmExecutor {

    private boolean isColorImage; // 是否为彩色图像
    private String description; // 算法描述

    /**
     * 默认构造函数，使用默认参数
     */
    public HistogramEqualizationExecutor() {
        this.isColorImage = false;
        this.description = "直方图均衡化算法 - 增强图像对比度，改善图像质量";
    }

    /**
     * 构造函数，允许自定义参数
     * 
     * @param isColorImage 是否为彩色图像
     */
    public HistogramEqualizationExecutor(boolean isColorImage) {
        this.isColorImage = isColorImage;
        this.description = "直方图均衡化算法 - 增强图像对比度，改善图像质量";
    }

    /**
     * 构造函数，允许自定义所有参数
     * 
     * @param isColorImage 是否为彩色图像
     * @param description 算法描述
     */
    public HistogramEqualizationExecutor(boolean isColorImage, String description) {
        this.isColorImage = isColorImage;
        this.description = description;
    }

    @Override
    public Mat execute(Mat input) {
        if (input == null || input.empty()) {
            throw new IllegalArgumentException("输入图像不能为空");
        }

        // 创建输出图像
        Mat output = new Mat();

        if (isColorImage && input.channels() > 1) {
            // 彩色图像直方图均衡化
            Mat ycrcbImage = new Mat();
            Imgproc.cvtColor(input, ycrcbImage, Imgproc.COLOR_BGR2YCrCb);
            
            // 分离通道
            java.util.List<Mat> channels = new java.util.ArrayList<>();
            Core.split(ycrcbImage, channels);
            
            // 对亮度通道进行直方图均衡化
            Imgproc.equalizeHist(channels.get(0), channels.get(0));
            
            // 合并通道
            Core.merge(channels, ycrcbImage);
            
            // 转回BGR颜色空间
            Imgproc.cvtColor(ycrcbImage, output, Imgproc.COLOR_YCrCb2BGR);
            
            // 释放中间资源
            ycrcbImage.release();
            for (Mat channel : channels) {
                channel.release();
            }
        } else {
            // 灰度图像直方图均衡化
            Mat grayImage = input.clone();
            if (input.channels() > 1) {
                Imgproc.cvtColor(input, grayImage, Imgproc.COLOR_BGR2GRAY);
            }
            
            Imgproc.equalizeHist(grayImage, output);
            
            // 释放中间资源
            if (!grayImage.equals(input)) {
                grayImage.release();
            }
        }

        return output;
    }

    // Getters and setters
    public boolean isColorImage() {
        return isColorImage;
    }

    public void setIsColorImage(boolean isColorImage) {
        this.isColorImage = isColorImage;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }
}